package com.mxpio.erp.workshop.controller;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.mxpio.erp.common.enums.OrderEnums;
import com.mxpio.erp.common.technology.entity.Item;
import com.mxpio.erp.common.vo.NoticeClassVo;
import com.mxpio.erp.common.workshop.entity.*;
import com.mxpioframework.jpa.JpaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.mxpio.erp.common.enums.OrderStatusEnums;
import com.mxpio.erp.common.jpa.model.OrderLine;
import com.mxpio.erp.common.jpa.model.OrderLineKey;
import com.mxpio.erp.common.order.service.OrderLineService;
import com.mxpio.erp.common.workshop.service.ManufactureOrderItemService;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.Operator;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;

@Tag(name = "ManufactureOrderItemController", description = "生产订单行接口")
@RestController
@RequestMapping("/erp/workshop/moline/")
public class ManufactureOrderItemController {

	@Autowired
	private ManufactureOrderItemService manufactureOrderItemService;
    
    @Autowired
    private OrderLineService bizOrderLineService;

    @GetMapping("list")
    @Operation(summary = "生产订单行列表", description = "获取生产订单行订单列表（无分页）", method = "GET")
    public Result<List<ManufactureOrderItem>> list(@Parameter(description="查询参数") Criteria criteria) throws UnsupportedEncodingException {
        List<ManufactureOrderItem> manufactureOrderItems = manufactureOrderItemService.list(ManufactureOrderItem.class, criteria);
        //处理数量字段
        NoticeClassVo pickingNoticeClazz = new NoticeClassVo(MoPickingNotice.class, MoPickingNoticeLine.class);//领/补/退
        NoticeClassVo defectiveProductsNoticeClazz = new NoticeClassVo(DefectiveProductsNotice.class, DefectiveProductsNoticeLine.class);//不良品退料
        List<NoticeClassVo> noticeClassVos = new ArrayList<>();
        noticeClassVos.add(pickingNoticeClazz);
        noticeClassVos.add(defectiveProductsNoticeClazz);
        bizOrderLineService.handleBizOrderLineQuantity(manufactureOrderItems, noticeClassVos, OrderEnums.AccessType.OUT.getCode());
        return Result.OK(manufactureOrderItems);
    }

    @GetMapping("page")
    @Operation(summary = "生产订单行列表", description = "获取生产订单行列表（分页）", method = "GET")
    public Result<Page<ManufactureOrderItem>> page(@Parameter(description="查询参数") Criteria criteria, @Parameter(description="每页条数")Integer pageSize, @Parameter(description="页号")Integer pageNo) throws UnsupportedEncodingException {
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        Page<ManufactureOrderItem> manufactureOrderItems = manufactureOrderItemService.listPage(ManufactureOrderItem.class, page, criteria);

        //处理数量字段
        /*NoticeClassVo pickingNoticeClazz = new NoticeClassVo(MoPickingNotice.class, MoPickingNoticeLine.class);//领/补/退
        NoticeClassVo defectiveProductsNoticeClazz = new NoticeClassVo(DefectiveProductsNotice.class, DefectiveProductsNoticeLine.class);//不良品退料
        List<NoticeClassVo> noticeClassVos = new ArrayList<>();
        noticeClassVos.add(pickingNoticeClazz);
        noticeClassVos.add(defectiveProductsNoticeClazz);
        bizOrderLineService.handleBizOrderLineQuantity(manufactureOrderItems.getContent(), noticeClassVos, OrderEnums.AccessType.OUT.getCode());*/

        return Result.OK(manufactureOrderItems);
    }
    @GetMapping("list/{bizNo}")
    @Operation(summary = "根据bizNo获取生产订单行", description = "根据bizNo获取生产订单行", method = "GET")
    public Result<List<ManufactureOrderItem>> getById(@Parameter(description="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo) {
        Criteria c = Criteria.create().addCriterion("bizNo", Operator.EQ, bizNo);
        List<ManufactureOrderItem> manufactureOrderItem = manufactureOrderItemService.list(ManufactureOrderItem.class, c);

        //处理数量字段
        NoticeClassVo pickingNoticeClazz = new NoticeClassVo(MoPickingNotice.class, MoPickingNoticeLine.class);//领/补/退
        NoticeClassVo defectiveProductsNoticeClazz = new NoticeClassVo(DefectiveProductsNotice.class, DefectiveProductsNoticeLine.class);//不良品退料
        List<NoticeClassVo> noticeClassVos = new ArrayList<>();
        noticeClassVos.add(pickingNoticeClazz);
        noticeClassVos.add(defectiveProductsNoticeClazz);
        bizOrderLineService.handleBizOrderLineQuantity(manufactureOrderItem, noticeClassVos, OrderEnums.AccessType.OUT.getCode());
        return Result.OK(manufactureOrderItem);
    }

    @GetMapping("computeset/{bizNo}/{setnum}")
    @Operation(summary = "根据bizNo获取生产订单行并按套数setnum计算订单行按套领料数量", description = "根据bizNo获取生产订单行并按套数setnum计算订单行按套领料数量", method = "GET")
    @Transactional
    public Result<List<ManufactureOrderItem>> computeset(@Parameter(description="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo,
                                                         @Parameter(description="领料套数") @PathVariable(name = "setnum", required = true) BigDecimal setnum) {
        Criteria c = Criteria.create().addCriterion("bizNo", Operator.EQ, bizNo);
        List<ManufactureOrderItem> manufactureOrderItem = manufactureOrderItemService.list(ManufactureOrderItem.class, c);

        //按套领料，计算行对应的领料数量
        if (manufactureOrderItem.size()>0){
            ManufactureOrder one = JpaUtil.getOne(ManufactureOrder.class, bizNo);
            BigDecimal orderQuantity = one.getOrderQuantity();//订单数量
            Set<String> itemCodeSet = manufactureOrderItem.stream().map(ManufactureOrderItem::getItemCode).collect(Collectors.toSet());
            List<Item> itemSet = JpaUtil.linq(Item.class).in("itemCode", itemCodeSet).list();
            Map<String, Item> itemMap = JpaUtil.index(itemSet, "itemCode");
            for (ManufactureOrderItem orderItem:manufactureOrderItem){
                BigDecimal lineQuantity = orderItem.getQuantity();
                Item item = itemMap.get(orderItem.getItemCode());
                if (item==null){
                    return Result.error("订单bom中物料编码"+orderItem.getItemCode()+"不存在，请检查数据");
                }
                Integer scale = item.getScale();//数据精度
                orderItem.setSetQuantity(setnum.multiply(lineQuantity).divide(orderQuantity,scale,RoundingMode.CEILING));//根据领料套数
            }
        }
        //处理数量字段
        NoticeClassVo pickingNoticeClazz = new NoticeClassVo(MoPickingNotice.class, MoPickingNoticeLine.class);//领/补/退
        NoticeClassVo defectiveProductsNoticeClazz = new NoticeClassVo(DefectiveProductsNotice.class, DefectiveProductsNoticeLine.class);//不良品退料
        List<NoticeClassVo> noticeClassVos = new ArrayList<>();
        noticeClassVos.add(pickingNoticeClazz);
        noticeClassVos.add(defectiveProductsNoticeClazz);
        bizOrderLineService.handleBizOrderLineQuantity(manufactureOrderItem, noticeClassVos, OrderEnums.AccessType.OUT.getCode());
        return Result.OK(manufactureOrderItem);
    }

    @GetMapping("list/{bizNo}/{lineNo}")
    @Operation(summary = "根据bizNo获取生产订单行", description = "根据bizNo获取生产订单行", method = "GET")
    public Result<ManufactureOrderItem> getById(@Parameter(description="业务单号") @PathVariable(name = "bizNo", required = true) String bizNo,@Parameter(description="行号") @PathVariable(name = "lineNo", required = true)String lineNo) {
        OrderLineKey lineKey = new OrderLineKey();
        lineKey.setLineNo(lineNo);
        lineKey.setBizNo(bizNo);
        ManufactureOrderItem manufactureOrderItem = manufactureOrderItemService.getById(ManufactureOrderItem.class, lineKey);
        return Result.OK(manufactureOrderItem);
    }

    @RequestMapping("save")
    @Operation(summary = "新增生产订单行", description = "新增生产订单行")
    public Result<ManufactureOrderItem> save(@RequestBody ManufactureOrderItem manufactureOrderItem) {
        manufactureOrderItemService.save(manufactureOrderItem);
        return Result.OK(manufactureOrderItem);
    }
    
    @RequestMapping("batch/save")
    @Operation(summary = "新增生产订单行(批量)", description = "新增生产订单行(批量)")
    public Result<List<ManufactureOrderItem>> save(@RequestBody List<ManufactureOrderItem> manufactureOrderItems) {
        manufactureOrderItemService.save(manufactureOrderItems);
        return Result.OK(manufactureOrderItems);
    }

    @DeleteMapping("remove/{ids}")
    @Operation(summary = "根据id删除生产订单行", description = "删除生产订单行,多个id用英文逗号分隔,bizNo和lineNo间使用英文冒号分隔,bizNo在前,lineNo在后", method = "DELETE")
    public Result<ManufactureOrderItem> remove(@PathVariable(name = "ids", required = true) String ids) {
        String[] id = ids.split(",");
        for(String key : id){
            String[] pk = key.split(":");
            OrderLineKey lineKey = new OrderLineKey();
            lineKey.setBizNo(pk[0]);
            lineKey.setLineNo(pk[1]);
            manufactureOrderItemService.remove(ManufactureOrderItem.class, lineKey);
        }
        return Result.OK();
    }

    @PutMapping("open/{ids}")
    @Operation(summary = "打开生产订单行", description = "打开生产订单行,多个id用英文逗号分隔,bizNo和lineNo间使用英文冒号分隔,bizNo在前,lineNo在后", method = "PUT")
    public Result<? extends OrderLine> open(@PathVariable(name = "ids", required = true) String ids) {
        return bizOrderLineService.updateCloseStatus(ManufactureOrderItem.class, ids, OrderStatusEnums.CloseStatus.OPEN);
    }

    @PutMapping("close/{ids}")
    @Operation(summary = "关闭生产订单行", description = "关闭生产订单行", method = "PUT")
    public Result<? extends OrderLine> close(@Parameter(description="业务单号，多个id用英文逗号分隔,bizNo和lineNo间使用英文冒号分隔,bizNo在前,lineNo在后") @PathVariable(name = "ids", required = true) String ids) {
        return bizOrderLineService.updateCloseStatus(ManufactureOrderItem.class, ids, OrderStatusEnums.CloseStatus.CLOSED);
    }

}
